package com.attendance.www.hr.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.SalaryApprovalRecordBean;
import com.attendance.www.hr.dao.mapper.EmployeeMapper;
import com.attendance.www.hr.dao.mapper.LinkAddressMapper;
import com.attendance.www.hr.dao.mapper.SalaryApprovalRecordExtMapper;
import com.attendance.www.hr.dao.mapper.SalaryApprovalRecordMapper;
import com.attendance.www.hr.dao.mapper.SalaryMapper;
import com.attendance.www.hr.dao.mapper.SalaryRequestMapper;
import com.attendance.www.hr.dao.mapper.SalaryRuleMapper;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.EmployeeExample;
import com.attendance.www.hr.entitys.LinkAddressExample;
import com.attendance.www.hr.entitys.Salary;
import com.attendance.www.hr.entitys.SalaryApprovalRecord;
import com.attendance.www.hr.entitys.SalaryApprovalRecordExample;
import com.attendance.www.hr.entitys.SalaryExample;
import com.attendance.www.hr.entitys.SalaryRequest;
import com.attendance.www.hr.entitys.SalaryRequestExample;
import com.attendance.www.hr.entitys.SalaryRule;
import com.attendance.www.hr.entitys.SalaryRuleExample;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IApprovalService;
import com.attendance.www.hr.service.ISalaryApprovalService;

@Service
public class SalaryApprovalServiceImpl implements ISalaryApprovalService {
	
	@Resource
	private SalaryRequestMapper salaryRequestDao;
	@Resource
	private SalaryRuleMapper salaryRuleDao;
	@Resource
	private SalaryApprovalRecordMapper salaryApprovalRecordDao;
	@Resource
	private SalaryApprovalRecordExtMapper salaryApprovalRecordExtDao;
	@Resource
	private EmployeeMapper employeeDao;
	@Resource
	private IApprovalService approvalService;
	@Resource
	private LinkAddressMapper linkAddressDao;
	@Resource
	private SalaryMapper salaryDao;

	/**
	 * 批量审批工资报表
	 */
	@Override
	public boolean saveSalaryApprovalRequestList(SalaryApprovalRecordBean salaryApprovalRecordBean) {
		//审批人
		Employee emp = employeeDao.selectByPrimaryKey(salaryApprovalRecordBean.getEmployeeId());
		String employeeNoApl = emp.getEmployeeNo();
		//取出页面选择的申请信息
		List<Integer> idList = salaryApprovalRecordBean.getSalaryRequestIdList();
		SalaryRequestExample srExample = new SalaryRequestExample();
		srExample.createCriteria().andSalaryRequestIdIn(idList)
		.andRequestStateNotEqualTo(0);
		
		List<SalaryRequest> srList = salaryRequestDao.selectByExample(srExample);
		//是否有撤回验证
		if (idList.size()>srList.size()) {
			throw new ResultFaultException("10_00007");
		}
		int record=0;
		for (SalaryRequest salaryRequest : srList) {
			//审批申请
			if(salaryRequest.getSalaryRuleId() == null){
				throw new ResultFaultException("10_00001");
			}
			//取得审批规则
			SalaryRule salaryRule = salaryRuleDao.selectByPrimaryKey(salaryRequest.getSalaryRuleId());
			
			//取审批记录
			SalaryApprovalRecordExample sarExample = new SalaryApprovalRecordExample();
			sarExample.createCriteria().andSalaryRequestIdEqualTo(salaryRequest.getSalaryRequestId())
			.andEmployeeNoApprovalEqualTo(employeeNoApl)
			.andApprovalStateEqualTo(1);
			List<SalaryApprovalRecord> sarList = salaryApprovalRecordDao.selectByExample(sarExample);
			SalaryApprovalRecord salaryApprovalRecord = sarList.get(0);
			
			if (salaryApprovalRecordBean.getApprovalState()==3) {//审批拒绝
				//更新审批记录
				salaryApprovalRecord.setApprovalDate(new Date());//添加审批日期
				salaryApprovalRecord.setApprovalState(3);//修改审批状态
				salaryApprovalRecord.setDescription(salaryApprovalRecordBean.getDescription());//审批意见
				salaryApprovalRecord.setUpdateTime(null);//设置更新时间
				record=salaryApprovalRecordDao.updateByPrimaryKeySelective(salaryApprovalRecord);
				if (record<=0) {
					return false;
				}
				//更新申请记录
				salaryRequest.setRequestState(3);
				salaryRequest.setUpdateTime(null);//设置更新时间
				salaryRequestDao.updateByPrimaryKeySelective(salaryRequest);
				
				//更新工资salary审批状态requestState
				SalaryExample salaryExample = new SalaryExample();
				salaryExample.createCriteria().andSalaryRequestIdEqualTo(salaryRequest.getSalaryRequestId());
				Salary salary = new Salary();
				salary.setRequestState(3);//申请被拒绝
				salaryDao.updateByExampleSelective(salary, salaryExample);
				
				//删除链接linkAddress
				this.deleteSalaryLinkAdd(salaryRequest.getSalaryRequestId());
				//邮件提醒
				//查申请人id
				String employeeNoSubmit = salaryRequest.getEmployeeNoSubmit();
				EmployeeExample empExample = new EmployeeExample();
				empExample.or().andEmployeeNoEqualTo(employeeNoSubmit)
				.andFromDateLessThanOrEqualTo(new Date())
				.andThruDateIsNull();
				empExample.or().andEmployeeNoEqualTo(employeeNoSubmit)
				.andFromDateLessThanOrEqualTo(new Date())
				.andThruDateGreaterThanOrEqualTo(new Date());
				
				List<Employee> empList = employeeDao.selectByExample(empExample);
				if (empList.size()>0) {
					Integer employeeId = empList.get(0).getEmployeeId();
					//提醒申请人
					String textPart = "工资报表申请被拒绝<br>审批人："+emp.getChineseName();
					approvalService.sendEmailByReject(employeeId, textPart,salaryApprovalRecordBean.getDescription());
				}
			} else if (salaryApprovalRecordBean.getApprovalState()==2) {//同意
				//更新审批记录
				salaryApprovalRecord.setApprovalDate(new Date());//添加审批日期
				salaryApprovalRecord.setApprovalState(2);//修改审批状态
				salaryApprovalRecord.setDescription(salaryApprovalRecordBean.getDescription());//审批意见
				salaryApprovalRecord.setUpdateTime(null);//设置更新时间
				record=salaryApprovalRecordDao.updateByPrimaryKeySelective(salaryApprovalRecord);
				if (record<=0) {
					return false;
				}
				int step = salaryApprovalRecord.getStep();
				int nowStep = step;
				//下一个审批人的编号
				String employeeNoApprovalNext = null;
				//判断是不是最终审批人
				if (step==1 && salaryRule.getTwoEmployeeNo()!=null) {
					step=2;
					employeeNoApprovalNext = salaryRule.getTwoEmployeeNo();
					
				} else if (step==2 && salaryRule.getThreeEmployeeNo()!=null) {
					step=3;
					employeeNoApprovalNext = salaryRule.getThreeEmployeeNo();
					
				} else if (step==3 && salaryRule.getFourEmployeeNo()!=null) {
					step=4;
					employeeNoApprovalNext = salaryRule.getFourEmployeeNo();
					
				} else if (step==4 && salaryRule.getFiveEmployeeNo()!=null) {
					step=5;
					employeeNoApprovalNext = salaryRule.getFiveEmployeeNo();
				}
				if (nowStep==step) {//无下一个审批人，是最终审批人
					//更新salary的审批状态
					SalaryExample salaryExample = new SalaryExample();
					salaryExample.createCriteria().andSalaryRequestIdEqualTo(salaryRequest.getSalaryRequestId());
					Salary salary = new Salary();
					salary.setRequestState(2);//审批拒绝
					record = salaryDao.updateByExampleSelective(salary, salaryExample);
					if (record<=0) {
						return false;
					}
					//更新申请记录
					salaryRequest.setRequestState(2);
					salaryRequest.setUpdateTime(null);//设置更新时间
					salaryRequestDao.updateByPrimaryKeySelective(salaryRequest);
					
					//删除链接linkAddress
					this.deleteSalaryLinkAdd(salaryRequest.getSalaryRequestId());
				} else {//有
					//添加审批记录
					SalaryApprovalRecord newSar = new SalaryApprovalRecord();
					newSar.setEmployeeNoSubmit(salaryRequest.getEmployeeNoSubmit());//申请人编号
					newSar.setEmployeeNoApproval(employeeNoApprovalNext);
					newSar.setSalaryMonth(salaryRequest.getSalaryMonth());
					newSar.setSalaryRequestId(salaryRequest.getSalaryRequestId());
					newSar.setSalaryYear(salaryRequest.getSalaryYear());
					newSar.setApprovalState(1);//添加审批状态，1待审批
					newSar.setStep(step);
					record = salaryApprovalRecordDao.insertSelective(newSar);
					if (record<=0) {
						return false;
					}
					
					//删除链接linkAddress
					this.deleteSalaryLinkAdd(salaryRequest.getSalaryRequestId());
					//给下个审批人邮件提醒
					//查审批人id
					List<Employee> empList = this.getNextEmployee(employeeNoApprovalNext);
					if (empList.size()>0) {
						Integer employeeId = empList.get(0).getEmployeeId();
						approvalService.sendEmail(employeeId, 
								"有"+salaryRequest.getChineseName()+"的考勤报表（工资使用）申请，请及时登陆HR考勤管理系统查看。",
								salaryRequest.getSalaryRequestId(), 88);
					}
				}
			}
		}
		return true;
	}
	
	/**
	 * 根据编号查人
	 * @param employeeNo
	 * @return
	 */
	private List<Employee> getNextEmployee(String employeeNo) {
		EmployeeExample empExample = new EmployeeExample();
		empExample.or().andEmployeeNoEqualTo(employeeNo)
		.andFromDateLessThanOrEqualTo(new Date())
		.andThruDateIsNull();
		empExample.or().andEmployeeNoEqualTo(employeeNo)
		.andFromDateLessThanOrEqualTo(new Date())
		.andThruDateGreaterThanOrEqualTo(new Date());
		return employeeDao.selectByExample(empExample);
	}

	/**
	 * 查看审批流程信息 by申请人
	 */
	@Override
	public List<SalaryApprovalRecordBean> getSalaryApprovalRecordList(SalaryApprovalRecordBean salaryApprovalRecordBean) {
		//取得审批规则
		SalaryRule salaryRule = salaryRuleDao.selectByPrimaryKey(salaryApprovalRecordBean.getSalaryRuleId());
		
		List<SalaryApprovalRecordBean> sarList = salaryApprovalRecordExtDao.getSalaryApprovalRecordList(salaryApprovalRecordBean);
		SalaryApprovalRecordBean sarbLast = sarList.get(sarList.size()-1);
		int step = sarbLast.getStep();
		String employeeNoApprovalNext=null;
		//判断是不是最终审批人
		List<Employee> empList = new ArrayList<>();
		if (step<=1 && salaryRule.getTwoEmployeeNo()!=null) {
			SalaryApprovalRecordBean sarbNew = new SalaryApprovalRecordBean();
			employeeNoApprovalNext = salaryRule.getTwoEmployeeNo();
			empList =this.getNextEmployee(employeeNoApprovalNext);
			if (empList.size()>0) {
				sarbNew.setChineseName(empList.get(0).getChineseName());
			}
			sarList.add(sarbNew);
		}
		if (step<=2 && salaryRule.getThreeEmployeeNo()!=null) {
			SalaryApprovalRecordBean sarbNew = new SalaryApprovalRecordBean();
			employeeNoApprovalNext = salaryRule.getThreeEmployeeNo();
			empList =this.getNextEmployee(employeeNoApprovalNext);
			if (empList.size()>0) {
				sarbNew.setChineseName(empList.get(0).getChineseName());
			}
			sarList.add(sarbNew);
		}
		if (step<=3 && salaryRule.getFourEmployeeNo()!=null) {
			SalaryApprovalRecordBean sarbNew = new SalaryApprovalRecordBean();
			employeeNoApprovalNext = salaryRule.getFourEmployeeNo();
			empList =this.getNextEmployee(employeeNoApprovalNext);
			if (empList.size()>0) {
				sarbNew.setChineseName(empList.get(0).getChineseName());
			}
			sarList.add(sarbNew);
		}
		if (step<=4 && salaryRule.getFiveEmployeeNo()!=null) {
			SalaryApprovalRecordBean sarbNew = new SalaryApprovalRecordBean();
			employeeNoApprovalNext = salaryRule.getFiveEmployeeNo();
			empList =this.getNextEmployee(employeeNoApprovalNext);
			if (empList.size()>0) {
				sarbNew.setChineseName(empList.get(0).getChineseName());
			}
			sarList.add(sarbNew);
		}
		return sarList;
	}

	/**
	 * 删除salary链接key
	 * @param salaryRequestId
	 */
	private void deleteSalaryLinkAdd(Integer salaryRequestId) {
		//删除链接linkAddress
		LinkAddressExample laExample = new LinkAddressExample();
		laExample.createCriteria().andSalaryRequestIdEqualTo(salaryRequestId);
		linkAddressDao.deleteByExample(laExample);
	}

	/**
	 * 判断是否是最终审批人
	 */
	@Override
	public int getIsLastPeople(int employeeId) {
		Employee employee = employeeDao.selectByPrimaryKey(employeeId);
		String employeeNo = employee.getEmployeeNo();
		//取得审批规则
		List<SalaryRule> salaryRuleList = salaryRuleDao.selectByExample(new SalaryRuleExample());
		if (salaryRuleList.size()==0) {//还没有审批规则
			return 0;
		} else {
			SalaryRule salaryRule = salaryRuleList.get(0);
			if (salaryRule.getFiveEmployeeNo()!=null) {//五级审批人
				if (employeeNo.equals(salaryRule.getFiveEmployeeNo())) {
					return 1;
				}
			} else {
				if (salaryRule.getFourEmployeeNo()!=null) {//四级审批人
					if (employeeNo.equals(salaryRule.getFourEmployeeNo())) {
						return 1;
					}
				} else {
					if (salaryRule.getThreeEmployeeNo()!=null) {//三级审批人
						if (employeeNo.equals(salaryRule.getThreeEmployeeNo())) {
							return 1;
						}
					} else {
						if (salaryRule.getTwoEmployeeNo()!=null) {//二级审批人
							if (employeeNo.equals(salaryRule.getTwoEmployeeNo())) {
								return 1;
							}
						} else {
							if (salaryRule.getOneEmployeeNo()!=null) {//一级审批人
								if (employeeNo.equals(salaryRule.getOneEmployeeNo())) {
									return 1;
								}
							}
						}
					}
				}
			}
		}
		return 0;
	}

	/**
	 * 驳回工资审批
	 */
	@Override
	public boolean saveRejectSalary(SalaryApprovalRecordBean salaryApprovalRecordBean) {
		//审批人
		Employee emp = employeeDao.selectByPrimaryKey(salaryApprovalRecordBean.getEmployeeId());
		String employeeNoApl = emp.getEmployeeNo();
		
		//申请的ID
		Integer salaryRequestId = salaryApprovalRecordBean.getSalaryRequestId();
		
		//更新salary审批状态
		SalaryExample salaryExample = new SalaryExample();
		salaryExample.createCriteria().andSalaryRequestIdEqualTo(salaryRequestId);
		Salary salary = new Salary();
		salary.setRequestState(3);//审批拒绝
		int record = salaryDao.updateByExampleSelective(salary, salaryExample);
		if (record<=0) {
			return false;
		}
		//
		//更新申请记录
		SalaryRequest salaryRequest = new SalaryRequest();
		salaryRequest.setSalaryRequestId(salaryRequestId);
		salaryRequest.setRequestState(3);
		record = salaryRequestDao.updateByPrimaryKeySelective(salaryRequest);
		if (record<=0) {
			return false;
		}
		//更新审批记录，最终审批人的审批记录
		SalaryApprovalRecordExample sarExample = new SalaryApprovalRecordExample();
		sarExample.createCriteria().andSalaryRequestIdEqualTo(salaryRequestId)
		.andEmployeeNoApprovalEqualTo(employeeNoApl);
		SalaryApprovalRecord sar = new SalaryApprovalRecord();
		sar.setApprovalState(3);//审批拒绝
		record = salaryApprovalRecordDao.updateByExampleSelective(sar, sarExample);
		if (record<=0) {
			return false;
		}
		
		return true;
	}
}
